<!--
Date: 2025-08-13
Copyright (c) 2025 Industrial Software Feature Database
-->
<template>
  <div class="p-2">
    <!-- <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave"> -->
      <div class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" size="small" :model="queryParams" :inline="true" label-width="120px">
            <el-form-item label="模板名称" prop="templateName">
              <el-input v-model="queryParams.templateName" placeholder="请输入模板名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <!-- <el-form-item label="模板描述" prop="templateDescription">
              <el-input v-model="queryParams.templateDescription" placeholder="请输入模板描述" clearable @keyup.enter="handleQuery" />
            </el-form-item> -->
            <el-form-item label="业务场景" prop="businessId">
              <el-select v-model="queryParams.businessId" placeholder="请选择业务场景" @change="getSystemList">
                <el-option v-for="item in businessList" :label="item.name" :value="item.id" :key="item.id"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="业务系统" prop="businessSystemId">
              <el-select v-model="queryParams.businessSystemId" placeholder="请选择业务系统">
                <el-option v-for="item in systemList" :label="item.name" :value="item.id" :key="item.id"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="要素库类型" prop="databaseType">
              <el-cascader
                style="margin-right: 20px;"
                v-model="queryParams.databaseType"
                :options="typeOptions"
                :props="cascaderProp"
              ></el-cascader>
            </el-form-item>

            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">查询</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    <!-- </transition> -->

    <el-card shadow="hover">
      <template #header>
        <el-row :gutter="10">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd()">新增模板</el-button>
          </el-col>
          <!-- <el-col :span="1.5">
            <el-button type="danger" plain :disabled="!selectionListAll || selectionListAll.length <= 0" icon="Delete" @click="handleDelete()">删除</el-button>
          </el-col> -->
        </el-row>
      </template>

      <el-table ref="tableRef" v-loading="loading" :data="templateList" @selection-change="handleSelectionChange">
        <el-table-column label="模板名称" prop="templateName" />
        
        <!-- <el-table-column label="模型名称" prop="isfdDatabaseModelConfigModelName" /> -->
        <el-table-column label="业务场景" prop="businessScenario" :show-overflow-tooltip="true">
          <template #default="scope">
            {{ scope.row.businessSceneName }}
          </template>
        </el-table-column>
        <el-table-column label="业务系统" prop="businessSystem" :show-overflow-tooltip="true">
          <template #default="scope">
            {{ scope.row.businessSystemName }}
          </template>
        </el-table-column>
        <el-table-column label="要素库类型" prop="databaseType">
          <template #default="scope">
            {{ scope.row.databaseTypeName }}
          </template>
        </el-table-column>
        <el-table-column label="模板版本号" prop="versionNumber" />
        <!-- <el-table-column label="具体模型" prop="modelName">
          <template #default="scope">   
            {{ scope.row.databaseModelingConfig && scope.row.databaseModelingConfig.modelName }}
          </template>
        </el-table-column> -->
        <el-table-column label="创建时间" prop="createTime" />
        <el-table-column label="模板描述" prop="templateDescription" />
        <el-table-column fixed="right" label="操作" width="190">
          <template #default="scope">
            <!-- <el-tooltip content="预览" placement="top">
              <el-button link type="primary" icon="View" @click="handleView(scope.row)"></el-button>
            </el-tooltip> -->
            <!-- <el-tooltip content="编辑" placement="top">
              <el-button size="small" link type="primary" icon="Edit" @click="handleUpdate(scope.row)">编辑</el-button>
            </el-tooltip> -->
            <el-tooltip content="导出模板" placement="top">
              <el-button size="small" link type="primary" icon="Download" @click="handleDownload(scope.row)">导出</el-button>
            </el-tooltip>
            <el-tooltip content="详情" placement="top">
              <el-button size="small" link type="primary" icon="View" @click="handleView(scope.row)">详情</el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button size="small" link type="primary" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <AddTemplate v-if="addVisible" :businessAll="businessAll" :typeOptions="typeOptions" :row="rowData" :enumList="enumList" :databaseTypeList="databaseTypeList" :addVisible="addVisible" @handleEvent="handleEvent" />
    <TemplateDetail v-if="viewVisible" :row="rowData" :viewVisible="viewVisible" @handleEvent="handleEvent"  />
  </div>
</template>

<script setup name="Tempalte">
// import * as XLSX from 'xlsx';
import * as XLSX from 'xlsx-js-style';
import AddTemplate from './AddTemplate.vue';
import TemplateDetail from './TemplateDetail.vue';
import { downloadFile } from '@/utils/index';
import { getModelList, getDatabaseList } from '@/api/metaData/index';
import { getBusinessSystemList } from '@/api/businessSystem';
import { getTreeList } from '@/api/databaseManagement';
import { getDatabaseTemplateList, deleteDatabaseTemplate, getDatabaseTemplateDetail, exportModelJSONTemplate } from '@/api/system/template';
const templateList = ref([]);
const queryFormRef = ref();
const templateTableRef = ref();
const loading = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const addVisible = ref(false);
const viewVisible = ref(false);
const total = ref(0);
const rowData = ref({});
const selectionList = ref([]);
const selectionListAll = ref([]);
const tableList = ref([]);
const tableRef = ref(null);
const enumList = ref([]);
const queryParams = ref({
    pageNum: 1,
    pageSize: 10,
    templateName: '',
    templateDescription: '',
    status: '',
    businessId: undefined,
    businessSystemId: undefined,
    databaseType: undefined,
    // isAsc: 'desc'
});
const businessList = ref([]);
const systemList = ref([]);
const businessAll = ref([]);
const typeOptions = ref([]);
const cascaderProp = {
  expandTrigger: 'hover',
  emitPath: false,
  label: 'databaseName',
  value: 'id'
}
const handleEvent = (prop) => {
  if (prop.type == 'success') {
    getList();
  }
  addVisible.value = false;
  viewVisible.value = false;
}
// 要素库类型列表
const getAllDatabase = () => {
  getTreeList({name: ''}).then((res) => {
    if (res) {
      typeOptions.value = res|| []
    }
  });
}
const getEnumList = () => {
  getBusinessSystemList({
    pageNum: 1,
    pageSize: 9999
  }).then(res => {
    businessAll.value = res.rows;
    businessList.value = res.rows.filter(item => item.type == 0)
  })
}
const getSystemList = (val) => {
  if (val) {
    queryParams.value.businessSystemId = '';
    systemList.value = businessAll.value.filter(item => item.parentId == val && item.type == 1)
  }
}
/**
 * 查询角色列表
 */
const getList = () => {
  loading.value = true;
  getDatabaseTemplateList(queryParams.value).then((res) => {
    templateList.value = res.data;
    loading.value = false;
    nextTick(() => {
      setSelectRow();
    })
  });
};
const handleView = (row) => {
  rowData.value = row;
  viewVisible.value = true;
}
const handleAdd = () => { 
  rowData.value = null;
  addVisible.value = true;
}
const handleUpdate = (row) => {
  rowData.value = row;
  addVisible.value = true;
}
const handleDownload = (row) => {
  exportModelJSONTemplate(row.id).then((res) => {
    if (res?.code === 500) {
      ElMessage({ showClose: true, message: '下载失败。', type: 'error' });
      return;
    }
    downloadFile(res, `${row.templateName}`, 'json');
  });
}
const handleSelectionChange = (val) => {
  // 表格选项发生变化
  selectionList.value = val
  nextTick(() => {
    changePageCoreRecordData()
  })
}
// 记忆选择核心方法
const changePageCoreRecordData = () => {
  // 标识当前行的唯一键的名称
  const idKey = 'id';
  // 如果总记忆中还没有选择的数据，那么就直接取当前页选中的数据，不需要后面一系列计算
  if (selectionListAll.value.length <= 0) {
    selectionListAll.value = selectionList.value;
    return
  }
  // 总选择里面的key集合
  const selectAllIds = []
  selectionListAll.value.forEach(row => {
    selectAllIds.push(row[idKey])
  })
  const selectIds = []
  // 获取当前页选中的id
  selectionList.value.forEach(row => {
    selectIds.push(row[idKey])
    // 如果总选择里面不包含当前页选中的数据，那么就加入到总选择集合里
    if (selectAllIds.indexOf(row[idKey]) < 0) {
      selectionListAll.value.push(row)
    }
  })
  const noSelectIds = []
  // 得到当前页没有选中的id
  tableList.value.forEach(row => {
    if (selectIds.indexOf(row[idKey]) < 0) {
      noSelectIds.push(row[idKey])
    }
  })
  noSelectIds.forEach(id => {
    if (selectAllIds.indexOf(id) >= 0) {
      for (let i = 0; i < selectionListAll.value.length; i++) {
        if (selectionListAll.value[i][idKey] == id) {
          // 如果总选择中有未被选中的，那么就删除这条
          selectionListAll.value.splice(i, 1)
          break
        }
      }
    }
  })
}
// 设置选中的方法
const setSelectRow = () => {
  if (!selectionListAll.value || selectionListAll.value.length <= 0) {
    return
  }
  // 标识当前行的唯一键的名称
  const idKey = 'id';
  const selectAllIds = []
  selectionListAll.value.forEach(row => {
    selectAllIds.push(row[idKey])
  })
  tableRef.value.clearSelection()
  for (var i = 0; i < tableList.value.length; i++) {
    if (selectAllIds.indexOf(tableList.value[i][idKey]) >= 0) {
      // 设置选中，记住table组件需要使用ref="table"
      tableRef.value.toggleRowSelection(tableList.value[i], true)
    }
  }
}
/**
 * 搜索按钮操作
 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};
/**删除按钮操作 */
const handleDelete = async (row) => {
  // 
  // await proxy?.$modal.confirm('是否确认删除角色编号为' + roleids + '数据项目');
  // await delRole(roleids);
  // getList();
  // proxy?.$modal.msgSuccess('删除成功');
  const ids = row?.id ? [row.id] : selectionListAll.value.map((el) => el.id);
  ElMessageBox.confirm(`是否确认删除模板id为${ids.join('，')}的模型模板？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    await deleteDatabaseTemplate(ids);
    ElMessage.success('删除成功');
    getList();
  }).catch(() => {
    ElMessage.error('删除失败');
  });
};

onMounted(() => {
  getEnumList();
  getAllDatabase();
  getList();
});
</script>
